import sys
import readline
import logging
from jablit.completer import MyCompleter
from jablit.utils import load_or_create_conf
conf = load_or_create_conf()

class CommandAnalyzer:
    def __init__(self, cl, client):
        self.client = client
        self.cl = cl
        self.online_aliases = {}

        mycompleter = MyCompleter(self.online_aliases)
        readline.set_completer(mycompleter.complete)

    def translate_input(self, str):
        cmd = str.split(":", 1)
        if len(cmd) > 1:
            tojid = cmd[0]
            if not '@' in tojid:
                if tojid in self.online_aliases:
                    tojid = self.online_aliases[tojid]
                else:
                    logging.error("jid <%s> not found " % tojid)
            return "send", (cmd[1]).strip(), tojid
        else:
            return "cmd", str.strip(), ""

    def _show(self):
        self.client.show = 1
        self.client.show_buffered_messages()

    def _hide(self):
        self.client.show = 0

    def _printbuffer(self):
        self.client.show_buffered_messages()

    def _status(self):
        if self.client.show:
            print 'shown'
        else:
            print 'hidden'

    def _reloadconfig(self):
        global conf
        conf = load_or_create_conf(reload=True)

    def _quit(self):
        sys.exit(0)

    def _setstatus(self):
        st, msg = "online", ""
        try:
            st, msg = self.msg.split(" ")[1], " ".join(self.msg.split(" ")[2:])
        except Exception:
            pass
        self.client.set_status(st, msg)

    def _who(self):
        roster = self.cl.getRoster()
        roster.Request()
        for i in self.online_aliases.keys():
            del self.online_aliases[i]
        for i in roster.getItems():
            jid = str(i)
            name = roster.getName(jid)
            status = roster.getStatus(jid)
            show = roster.getShow(jid)
            resources = roster.getResources(jid)
            if jid in conf[0].aliases:
                name = conf[0].aliases[jid]
            elif not name:
                name = jid
            showd = 'x'
            if not show:
                showd = 'o'
            elif show == 'away':
                showd = '*'
            res = [showd, name, status, u"-".join(resources)]
            res = [i for i in res if i]
            if resources:
                print " " + res[0] , " ".join(res[1:]).encode('utf-8')
                self.online_aliases[name] = jid

    def run_cmd(self):
        if self.typ == "send":
            self.client.stdio_message(self.msg, self.jid)
        if self.typ == "cmd":
            cmd = self.msg.split(" ")[0]
            try:
                exec("self._" + cmd + "()")
            except AttributeError:
                pass

    def run_once(self, instr):
        self.typ, self.msg, self.jid = self.translate_input(instr)
        self.run_cmd()
